﻿using AutoMapper;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
using ZP.Common;
using ZP.DTO.Common;
using ZP.DTO.fz_base_employee;
using ZP.IBLL;
using ZP.IDAL;
using ZP.Model;
using Z.EntityFramework.Plus;

namespace ZP.BLL
{
    public partial class fz_base_employeeService : BaseService<fz_base_employee, int>, Ifz_base_employeeService
    {
        //public fz_base_employeeService(Ifz_base_employeeDAL _fz_base_employeeDAL, Ifz_sys_userDAL _fz_sys_userDAL)
        //{
        //    this._fz_base_employeeDAL = _fz_base_employeeDAL;
        //    this._fz_sys_userDAL = _fz_sys_userDAL;

        //    this._repository = _fz_base_employeeDAL;
        //}

        /// <summary>
        /// 查询所有员工信息(含模糊查询)分页
        /// </summary>
        /// <returns></returns>
        public PageModel<fz_base_employeeResultDTO> GetBaseEmployee(fz_base_employeeSearchDTO dto)
        {
            PageModel<fz_base_employeeResultDTO> result = new PageModel<fz_base_employeeResultDTO>();

            Expression<Func<fz_base_employee, bool>> WhereLambda = (p => p.state == ZPFlagType.YES);
            if (null != dto)
            {
                if (!string.IsNullOrWhiteSpace(dto.SearchText))
                {
                    WhereLambda = WhereLambda.And(p => p.name.Contains(dto.SearchText) || p.code.Contains(dto.SearchText));
                }
                if (dto.type != null && dto.type.Count() > 0)
                {
                    WhereLambda = WhereLambda.And(p => dto.type.Contains(p.type));
                }


            }

            int total = 0;
            Expression<Func<fz_base_employee, int>> OrderByLambda = (o => o.id);

            IQueryable<fz_base_employee> iquery = null;
            if (dto.isPaging.HasValue)
            {
                if (dto.isPaging.Value)
                {
                    iquery = _repository.GetModelsByPage(dto.limit, dto.page, out total, WhereLambda, OrderByLambda, false);
                }
                else
                {
                    iquery = _repository.GetModels(WhereLambda).OrderBy(OrderByLambda);
                    total = iquery.Count();
                }
            }

            result.count = total;
            result.data = Mapper.Map<List<fz_base_employee>, List<fz_base_employeeResultDTO>>(iquery.ToList());
            return result;
        }

        /// <summary>
        /// 保存员工-新增/修改
        /// </summary>
        /// <returns></returns>
        public bool SaveBaseEmployee(fz_base_employeeOperateDTO dto)
        {
            bool result = false;
            if (0 == dto.id || !dto.id.HasValue)
            {
                //判断是否已经存在员工编号(可能员工名称会重名但编号不能重复)
                bool existsCount = _repository.GetModels(p => p.code == dto.code).Any();
                if (existsCount)
                {
                    throw new Exception(TipsMessage.该员工编号已存在);
                }
                //新增
                var item = Mapper.Map<fz_base_employeeOperateDTO, fz_base_employee>(dto);
                item.state = ZPFlagType.YES;
                item.updater = dto.updater;
                item.updatetime = DateTime.Now;
                _repository.Add(item, false);
                // 记录日志
                //this.AddLog(ZPe, new LogData
                //{
                //    CurrentLogType = LogType.ADD,
                //    LogDetails = "新增员工" + dto.name,
                //    OpratorName = dto.updater
                //});
            }
            else
            {
                //判断是否已经存在角色名称和角色编码
                bool existsCount = _repository.GetModels(p => p.code == dto.code && p.id != dto.id).Any();
                if (existsCount)
                {
                    throw new Exception(TipsMessage.该员工编号已存在);
                }

                //修改
                fz_base_employee entity = _repository.Find(dto.id.Value);
                if (dto.state.HasValue)  //删除用户(逻辑删除)
                {
                    entity.state = dto.state.Value;
                    if (dto.state.HasValue && dto.state.Value == ZPFlagType.NO)
                    {
                        entity.updatetime = DateTime.Now;
                    }
                    else
                    {
                        entity.updatetime = null;
                    }
                }
                else
                {
                    Mapper.Map<fz_base_employeeOperateDTO, fz_base_employee>(dto, entity);
                    entity.state = ZPFlagType.YES;
                    entity.updater = dto.updater;
                    entity.updatetime = DateTime.Now;
                }
                //Modify(ZPe, entity);
                _repository.Update(entity, false);

                // 记录日志
                //this.AddLog(ZPe, new LogData
                //{
                //    CurrentLogType = LogType.MODIFY,
                //    LogDetails = "修改员工" + dto.name,
                //    OpratorName = dto.updater
                //});
            }
            result = _repository.SaveChanges();

            return result;
        }

        /// <summary>
        /// 批量删除员工(逻辑删除改变state状态)
        /// </summary>
        /// <returns></returns>
        public bool DeleteBaseEmployee(List<fz_base_employeeOperateDTO> dto, UserLoginDTO loginUser)
        {
            bool result = false;
            try
            {
                if (dto == null || dto.Count <= 0)
                {
                    return result;
                }
                List<int> longIds = dto.Select(i => i.id.Value).ToList();
                //查询员工账户是否删除了
                StringBuilder errorMsg = new StringBuilder();
                var userList = _fz_sys_userDAL.GetModels(p => longIds.Contains(p.employeeId.Value) && p.state == ZPFlagType.YES);
                foreach (var user in userList)
                {
                    errorMsg.AppendFormat("<br/>{0} 对应的用户账号 {1} 尚未删除!", dto.Where(p => p.id == user.employeeId).FirstOrDefault().name, user.account);
                }
                if (errorMsg.Length > 0)
                {
                    throw new Exception(errorMsg.ToString());
                }

                //查询员工表下是否存在
                var iqueryEmployeeList = _repository.GetModels(p => longIds.Contains(p.id));
                //逻辑删除用户(state=0)
                int deleteCount = iqueryEmployeeList.Update(p => new fz_base_employee() { state = ZPFlagType.NO });
                //Delete(ZPe, iqueryEmployeeList);
                if (deleteCount > 0)
                {
                    string strEmployeeName = string.Join(",", iqueryEmployeeList.Select(o => o.name).ToList());
                    // 记录日志
                    /*this.AddLog(ZPe, new LogData
                    {
                        CurrentLogType = LogType.DELETE,
                        LogDetails = "删除员工" + strEmployeeName,
                        OpratorName = loginUser.account
                    });*/
                }

                result = deleteCount > 0;
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
            return result;
        }

    }
}
